<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="70px">
      <el-form-item label="小组名称" prop="groupName">
        <el-input v-model="queryParams.groupName" placeholder="请输入小组名称" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="小组组长" prop="groupLeader">
        <el-input v-model="queryParams.groupLeader" placeholder="请输入小组组长" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="小组组员" prop="groupMember">
        <el-input v-model="queryParams.groupMember" placeholder="请输入小组组员" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="专家成员" prop="groupExpert">
        <el-input v-model="queryParams.groupExpert" placeholder="请输入专家成员" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleQuery">查询</el-button>
        <el-button plain @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" @click="handleAdd">
          <svg-icon class-name="groupAdd-icon" icon-class="groupAdd" /><span style="margin-left:10px">新增小组</span>
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button plain icon="Delete" :disabled="multiple" @click="handleDelete">删除</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <el-table v-loading="loading"  ref="multipleTableRef" :data="groupList" stripe @selection-change="handleSelectionChange" row-key="id">
      <el-table-column type="selection" width="55" align="center" :reserve-selection="true" />
      <el-table-column label="序号" align="center" width="55" prop="ind">
        <template #default="scope">
               <span>{{ (queryParams.page - 1) * queryParams.rows + scope.$index + 1 }}</span>
            </template>
      </el-table-column>
      <el-table-column label="小组名称" align="center" prop="groupName" />
      <el-table-column label="小组组长" align="center" prop="groupLeader" />
      <el-table-column label="小组组员" align="center" prop="groupMember" show-overflow-tooltip />
      <el-table-column label="专家成员" align="center" prop="groupExpert" show-overflow-tooltip />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button type="text" @click="handleUpdate(scope.row)">修改</el-button>
          <el-button type="text" @click="handleDetil(scope.row)">查看</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.page" v-model:limit="queryParams.rows"
      @pagination="getList" />

    <!-- 添加小组对话框 -->
    <el-dialog :title="title" v-model="open" width="900px" append-to-body>
      <p class="dialogTitle">{{ title }}</p>
      <el-form ref="groupRef" :model="form" :rules="rules" label-width="80px" :inline="true" class="addGroup">
        <el-form-item label="小组名称" prop="groupName">
          <el-input v-model="form.groupName" placeholder="请输入小组名称" style="width: 250px" />
        </el-form-item>
        <el-form-item label="小组组长" prop="groupLeader">
          <el-select v-model="form.groupLeader" placeholder="请选择小组组长" readonly @click="openSelectUser(1)"
            style="width: 250px" />
        </el-form-item>
        <h3><span></span> 组员信息</h3>
        <el-form-item label="选择组员" prop="groupMember">
          <el-col :span="21">
            <el-input v-model="form.groupMember" @click="openSelectUser(2)" placeholder="请选择小组组员" readonly
              style="width: 250px" />
          </el-col>
          <el-col :span="3">
            <el-button plain :disabled="form.groupMember == undefined" @click="addMembers">添加</el-button>
          </el-col>
        </el-form-item>
        <el-table ref="multipleTableRef1" style="margin-bottom: 20px" :data="queryList.MemberList" stripe>
          <el-table-column label="序号" width="55" align="center" prop="ind" />
          <el-table-column label="组员姓名" align="center" prop="realName" />
          <el-table-column label="单位" align="center" prop="orgName" />
          <el-table-column label="手机号" align="center" prop="mobile" />
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template #default="scope">
              <el-button type="text" @click="handleDeleteMember(scope.row, 2)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <h3><span></span> 专家成员</h3>
        <el-form-item label="选择专家" prop="groupExpert">
          <el-col :span="21">
            <el-input v-model="form.groupExpert" @click="openSelectUser(3)" placeholder="请选择专家" readonly
              style="width: 250px" />
          </el-col>
          <el-col :span="3">
            <el-button plain :disabled="form.groupExpert == undefined" @click="addExpert">添加</el-button>
          </el-col>
        </el-form-item>
        <el-table ref="multipleTableRef1" :data="queryList.ExpertList" stripe>
          <!--<el-table-column type="selection" width="55" align="center" />-->
          <el-table-column label="序号" width="55" align="center" prop="ind" />
          <el-table-column label="专家姓名" align="center" prop="realName" />
          <el-table-column label="单位" align="center" prop="orgName" />
          <el-table-column label="手机号" align="center" prop="mobile" />
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template #default="scope">
              <el-button type="text" @click="handleDeleteMember(scope.row, 3)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">保存</el-button>
          <el-button plain @click="cancel">取消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 人员选择对话框 -->
    <el-dialog v-model="show" width="1200px" append-to-body>
      <p></p>
      <template #title>
        人员选择（<span v-show="isshow != 1">多选</span><span v-show="isshow == 1">单选</span>）
      </template>
      <select-user ref="selectRef" :isshow="isshow" @getSelectList="getSelectList" />
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="ok">确 定</el-button>
          <el-button plain @click="cancelP">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 查看对话框 -->
    <el-dialog v-model="openDetail" width="900px" title="查看小组" append-to-body>
      <p class="dialogTitle">查看小组</p>
      <el-descriptions :column="1" style="width:750px;margin:0 auto">
        <el-descriptions-item label="小组名称">{{
            detilList.fwGroupEntity.groupName
              ? detilList.fwGroupEntity.groupName
              : "-"
        }}</el-descriptions-item>
        <el-descriptions-item label="小组组长">{{
            detilList.fwGroupEntity.groupLeader
              ? detilList.fwGroupEntity.groupLeader
              : "-"
        }}</el-descriptions-item>
        <el-descriptions-item label="小组成员">
          <el-table style="margin-bottom: 20px; width: 100%" :data="detilList.memberlist ? detilList.memberlist : []"
            stripe>
            <el-table-column label="序号" width="55" align="center" prop="ind" />
            <el-table-column label="组员姓名" align="center" prop="realName" />
            <el-table-column label="单位" align="center" prop="orgName" />
            <el-table-column label="手机号" align="center" prop="mobile" />
          </el-table>
        </el-descriptions-item>
        <el-descriptions-item label="专家成员">
          <el-table style="margin-bottom: 20px" :data="detilList.expertlist ? detilList.expertlist : []" stripe>
            <el-table-column label="序号" width="55" align="center" prop="ind" />
            <el-table-column label="组员姓名" align="center" prop="realName" />
            <el-table-column label="单位" align="center" prop="orgName" />
            <el-table-column label="手机号" align="center" prop="mobile" />
          </el-table>
        </el-descriptions-item>
      </el-descriptions>
    </el-dialog>
  </div>
</template>

<script setup name="group">
import selectUser from "./selectUser";
import {
  addGroup,
  delGroup,
  getGroup,
  updateGroup,
  detilGroup,
} from "@/api/taskmanage/group.js";

const { proxy } = getCurrentInstance();

const open = ref(false);
const openDetail = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const isshow = ref(undefined);
const show = ref(false);
const time = ref();

const data = reactive({
  groupList: [],
  form: {
    groupName: undefined,
    groupLeader: undefined,
    groupLeaderId: undefined,
    leaderOrgId:undefined,
    groupMember: undefined,
    MemberList: [],
    groupExpert: undefined,
    ExpertList: [],
  },
  queryList: {
    MemberList: [],
    ExpertList: [],
  },
  queryParams: {
    page: 1,
    rows: 10,
    groupName: undefined,
    groupLeader: undefined,
    groupMember: undefined,
    groupExpert: undefined,
  },
  rules: {
    groupName: [
      { required: true, message: "小组名称不能为空", trigger: "blur" },
    ],
    groupLeader: [
      { required: true, message: "小组组长不能为空", trigger: "change" },
    ],
    groupMember: [
      { required: true, message: "小组成员不能为空", trigger: "change" },
    ],
  },
  detilList: {
    fwGroupEntity: {
      groupName: undefined,
      groupLeader: undefined,
      leaderOrgId: undefined,
    },
    memberlist: undefined,
    expertlist: undefined,
  },
});

const { groupList, queryParams, form, rules, queryList, detilList } =
  toRefs(data);

// 序号
function indexData(arr) {
  arr.forEach((item, index) => {
    item.ind = index + 1;
  });
  return arr;
}

/** 查询小组列表 */
function getList() {
  loading.value = true;
  getGroup(queryParams.value).then((response) => {
    groupList.value = indexData(response.data.result);
    total.value = response.data.total;
    loading.value = false;
  });
}
/** 取消按钮 */
function cancel() {
  open.value = false;
  reset();
}
/** 表单重置 */
function reset() {
  form.value = {
    groupName: undefined,
    groupLeader: undefined,
    leaderOrgId: undefined,
    groupMember: undefined,
    groupExpert: undefined,
    id: "",
  };
  queryList.value = {
    MemberList: [],
    ExpertList: [],
  };
  proxy.resetForm("groupRef");
}
/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.page = 1;
  getList();
}
/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}
/** 多选框选中数据 */
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}
/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "新建小组";
}
/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  open.value = true;
  title.value = "修改小组";
  const groupId = row.id;
  detilGroup({ groupId: groupId }).then((response) => {
    form.value = {
      groupName: response.data.fwGroupEntity.groupName,
      groupLeader: response.data.fwGroupEntity.groupLeader,
      groupLeaderId: response.data.fwGroupEntity.groupLeaderId,
      leaderOrgId : response.data.fwGroupEntity.leaderOrgId,
      id: groupId,
      MemberList: response.data.memberlist,
      ExpertList: response.data.expertlist,
      groupExpert: response.data.fwGroupEntity.groupExpert,
      groupMember: response.data.fwGroupEntity.groupMember,
    };
    queryList.value = {
      MemberList: indexData(response.data.memberlist),
      ExpertList: indexData(response.data.expertlist),
    };
  });
}
/** 查看按钮操作 */
function handleDetil(row) {
  openDetail.value = true;
  const groupId = row.id;
  detilGroup({ groupId: groupId }).then((response) => {
    nextTick(() => {
      detilList.value.fwGroupEntity = response.data.fwGroupEntity;
      detilList.value.memberlist = indexData(response.data.memberlist);
      detilList.value.expertlist = indexData(response.data.expertlist);
    });
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["groupRef"].validate((vaild) => {
    if (!vaild) {
      return;
    }
    const parmas = {
      fwGroupEntity: {},
    };
    parmas.fwGroupEntity["groupName"] = form.value.groupName;
    parmas.fwGroupEntity["groupLeader"] = form.value.groupLeader;
    parmas.fwGroupEntity["groupLeaderId"] = form.value.groupLeaderId;
    parmas.fwGroupEntity["leaderOrgId"] = form.value.leaderOrgId;
    parmas.fwGroupEntity["id"] = form.value.id;
    parmas["memberlist"] = queryList.value.MemberList;
    parmas["expertlist"] = queryList.value.ExpertList;
    
    if(parmas["memberlist"].length == 0){
      proxy.$modal.msgWarning('请添加组员信息！')
      return
    }
    // 新增
    if (title.value != "修改小组") {
      proxy.$modal.loading();
      addGroup(parmas).then((response) => {
        proxy.$modal.closeLoading();
        open.value = false;
        proxy.$modal.msgSuccess("新增成功");
        getList();
      }).catch(err=>{proxy.$modal.closeLoading();});
    } else {
      // 修改
      proxy.$modal.loading();
      updateGroup(parmas).then((response) => {
        proxy.$modal.closeLoading();
        open.value = false;
        proxy.$modal.msgSuccess("修改成功");
        getList();
      }).catch(err=>{proxy.$modal.closeLoading();});
    }
  });
}
// 提交人员
function ok() {
  show.value = false;
  nextTick(() => {
    proxy.$refs["selectRef"].submit();
  });
}

/** 删除按钮操作 */
const multipleTableRef = ref();
function handleDelete() {
  console.log(ids.value.join(","));
  proxy.$modal
    .confirm("是否确认删除吗？")
    .then(function () {
      return delGroup(ids.value.join(","));
    })
    .then(() => {
      getList();
      multipleTableRef.value?.clearSelection()
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => { });
}
// 删除小组成员
function del(id, list) {
  list.forEach((item, i) => {
    if (item.uuid == id) {
      list.splice(i, 1);
    }
  });
}
function handleDeleteMember(row, num) {
  const realName = row.realName;
  proxy.$modal
    .confirm("是否确认删除" + realName + "？")
    .then(() => {
      if (num == 2) {
        del(row.uuid, queryList.value.MemberList);
        del(row.uuid, form.value.MemberList);
        form.value.groupMember = getGroupName(form.value.MemberList);
        proxy.$modal.msgSuccess("删除成功");
        proxy.$refs['multipleTableRef1']?.clearSelection()
      } else {
        del(row.uuid, queryList.value.ExpertList);
        del(row.uuid, form.value.ExpertList);
        form.value.groupExpert = getGroupName(form.value.ExpertList);
        proxy.$modal.msgSuccess("删除成功");
        proxy.$refs['multipleTableRef2']?.clearSelection()
      }
    })
    .catch(() => { });
}

// 添加小组成员
function addMembers() {
  queryList.value.MemberList = indexData(form.value.MemberList);
}
// 添加专家成员
function addExpert() {
  queryList.value.ExpertList = indexData(form.value.ExpertList);
}
/** 打开人员弹窗 */
function openSelectUser(num) {
  time.value = new Date().getTime();
  isshow.value = num;
  show.value = true;

  nextTick(() => {
    proxy.$refs["selectRef"].reset();
    proxy.$refs["selectRef"].getTreeselect();
  });
}

/** 关闭人员弹窗 */
function cancelP() {
  show.value = false;
  proxy.$refs["selectRef"].reset();
}

// 获取人名
function getGroupName(data) {
  let arr = [];
  data.forEach((item) => {
    arr.push(item.realName);
  });
  return arr.join(",");
}

// 选择的数据
function getSelectList(val) {
  let value = JSON.parse(JSON.stringify(val));
  switch (isshow.value) {
    case 1:
      form.value.groupLeader = value[0].realName;
      form.value.groupLeaderId = value[0].uuid;
      form.value.leaderOrgId = value[0].orgId;
      break;
    case 2:
      let arr = form.value.MemberList;
      console.log(arr);
      if (arr == undefined) {
        console.log(1111);
        arr = value;
      } else {
        console.log(2222);
        value = value.filter((item1) => {
          return arr.every((item2) => {
            return item2.uuid != item1.uuid;
          });
        });
        arr = arr.concat(value);
      }
      form.value.MemberList = arr;
      form.value.groupMember = getGroupName(arr);
      break;
    case 3:
      let arr1 = form.value.ExpertList;
      if (arr1 == undefined) {
        arr1 = value;
      } else {
        value = value.filter((item1) => {
          return arr1.every((item2) => {
            return item2.uuid != item1.uuid;
          });
        });
        arr1 = arr1.concat(value);
      }
      form.value.ExpertList = arr1;
      form.value.groupExpert = getGroupName(arr1);
      break;
    default:
      break;
  }
}
getList();
</script>

<style lang="scss" scoped>
h3 {
  color: #333;
  height: 21px;
  font-size: 14px;
  line-height: 21px;
  display: flex;
  align-items: center;
  font-weight: bold;

  span {
    margin-right: 12px;
    display: inline-block;
    width: 3px;
    height: 14px;
    background: #333;
  }
}

.addGroup {
  width: 760px;
  margin: 0 auto;
}

:deep(.el-descriptions__label) {
  font-weight: bold;
  font-size: 14px;
  color: #333;
}
</style>